package xin.cymall.controller;

import java.util.List;
import java.util.Map;
import xin.cymall.utils.*;
import xin.cymall.annotation.SysLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


import org.springframework.stereotype.Controller;
import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONArray;
import xin.cymall.exception.ExcelException;
import xin.cymall.quartz.JobTask;
import net.sf.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.LinkedHashMap;

import xin.cymall.entity.SysJob;
import xin.cymall.service.SysJobService;


/**
 * 
 * 
 * @author mhj
 * @email 254784163@qq.com
 * @date 2018-05-23 15:21:12
 */
@Controller
@RequestMapping("sysjob")
public class SysJobController extends AbstractController{
	@Autowired
	private JobTask jobTask;
	@Autowired
	private SysJobService sysJobService;
	@RequestMapping("/list")
    public String list() {
        return "sysJob/list";
    }
	/**
	 * 列表
	 */
    @ResponseBody
	@RequestMapping("/listData")
	@RequiresPermissions("sysjob:list")
	public R list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);

		List<SysJob> sysJobList = sysJobService.queryList(query);
		int total = sysJobService.queryTotal(query);
		
		PageUtils pageUtil = new PageUtils(sysJobList, total, query.getLimit(), query.getPage());
		
		return R.ok().put("page", pageUtil);
	}

    /**
     * 跳转到新增页面
     **/
    @RequestMapping("/add")
    @RequiresPermissions("sysjob:save")
    public String add(){
        return "sysjob/add";
    }

    /**
     *   跳转到修改页面
     **/
    @RequestMapping("/edit/{id}")
    @RequiresPermissions("sysjob:update")
    public String edit(Model model, @PathVariable("id") String id){
		SysJob sysJob = sysJobService.get(id);
        model.addAttribute("model",sysJob);
        return "sysjob/edit";
    }

	/**
	 * 信息
	 */
    @ResponseBody
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sysjob:info")
    public R info(@PathVariable("id") String id){
        SysJob sysJob = sysJobService.get(id);
        return R.ok().put("sysJob", sysJob);
    }

    /**
	 * 保存
	 */
    @ResponseBody
    @SysLog("保存")
	@RequestMapping("/save")
	@RequiresPermissions("sysjob:save")
	public R save(@RequestBody SysJob sysJob){
		sysJobService.save(sysJob);
		try {
			execute(sysJob);
		} catch (Exception e) {
			throw new RRException("检查配置是否正确");
		}
		return R.ok();
	}
	
	/**
	 * 修改
	 */
    @ResponseBody
    @SysLog("修改")
	@RequestMapping("/update")
	@RequiresPermissions("sysjob:update")
	public R update(@RequestBody SysJob sysJob){
    	if (jobTask.checkJob(sysJob)) {
            return R.error("已经启动任务无法更新,请停止后更新");
        }
    	try {
			execute(sysJob);
		} catch (Exception e) {
			throw new RRException("检查配置是否正确");
		}
		sysJobService.update(sysJob);
		return R.ok();
	}
    private void execute(SysJob sysJob) {
    	int status = sysJob.getStatus();
    	switch (status) {
		case 1:
			jobTask.startJob(sysJob);
			break;
		case 2:
			jobTask.startJob(sysJob);
			break;
		case 3:
			jobTask.pauseJob(sysJob);
			break;
		case 4:
			jobTask.resumeJob(sysJob);
			break;
		}
    }
    /**
     * 启动
     */
    @ResponseBody
    @SysLog("启动")
    @RequestMapping("/start")
    @RequiresPermissions("sysjob:update")
    public R start(@RequestBody String[] ids){
    	SysJob sysJob = sysJobService.get(ids[0]);
    	sysJob.setStatus(1);
    	jobTask.startJob(sysJob);
		sysJobService.update(sysJob);
        return R.ok();
    }
    /**
     * 停止
     */
    @ResponseBody
    @SysLog("停止")
    @RequestMapping("/stop")
    @RequiresPermissions("sysjob:update")
    public R stop(@RequestBody String[] ids){
    	SysJob sysJob = sysJobService.get(ids[0]);
    	sysJob.setStatus(2);
    	jobTask.stopJob(sysJob);
		sysJobService.update(sysJob);
        return R.ok();
    }
    /**
     * 暂停
     */
    @ResponseBody
    @SysLog("暂停")
    @RequestMapping("/pause")
    @RequiresPermissions("sysjob:update")
    public R pause(@RequestBody String[] ids){
    	SysJob sysJob = sysJobService.get(ids[0]);
    	sysJob.setStatus(3);
    	jobTask.pauseJob(sysJob);
		sysJobService.update(sysJob);
        return R.ok();
    }
    /**
     * 恢复
     */
    @ResponseBody
    @SysLog("恢复")
    @RequestMapping("/resume")
    @RequiresPermissions("sysjob:update")
    public R resume(@RequestBody String[] ids){
    	SysJob sysJob = sysJobService.get(ids[0]);
    	sysJob.setStatus(1);
    	jobTask.resumeJob(sysJob);
		sysJobService.update(sysJob);
        return R.ok();
    }
	
	/**
	 * 删除
	 */
    @ResponseBody
    @SysLog("删除")
	@RequestMapping("/delete")
	@RequiresPermissions("sysjob:delete")
	public R delete(@RequestBody String[] ids){
    	SysJob job = sysJobService.get(ids[0]);
    	boolean flag = jobTask.checkJob(job);
        if (flag) {
            return R.error("该任务处于启动中，无法删除");
        }
        jobTask.remove(job);
		sysJobService.delete(ids[0]);
		
		return R.ok();
	}
	/**
	 * 导出
	 */
	@ResponseBody
	@SysLog("生成excel")
	@RequestMapping("/genExcel")
	@RequiresPermissions("sysjob:export")
	public R genExcel(@RequestParam Map<String, Object> params,HttpServletRequest request) throws IOException, ExcelException{
		//查询列表数据
		params.put("offset", null);
		params.put("page", null);
		JSONArray array = JSONArray.fromObject(params.get("exportHead"));
		LinkedHashMap<String,Object> fieldMap = new LinkedHashMap<String,Object>();
		for(int i = 0; i < array.size();i++) {
			JSONObject jsonObj = (JSONObject)array.get(i);
			Iterator<?> it = jsonObj.keys();
			while(it.hasNext()) {
				String keys = it.next().toString();
				String values = jsonObj.getString(keys);
				fieldMap.put(keys,values);
			}
		}
		Query query = new Query(params);
		List<SysJob> sysJobList = sysJobService.queryList(query);
		
		String savePath = request.getServletContext().getRealPath("/WEB-INF/tmp");
		logger.debug("获取到的/WEB-INF/tmp  路径=== " + savePath);
        
        File tmpDir = new File(savePath);
        // 判断上传文件的保存目录是否存在
        if (!tmpDir.exists() && !tmpDir.isDirectory()){
            logger.debug(savePath + "目录不存在，需要创建。");
            // 创建目录
            tmpDir.mkdir();
        }
        String fileWriteTime = DateUtil.getYmdhmsFName();
        
        String tmpFileName = savePath + "\\" + fileWriteTime + ".xls";
        logger.debug("临时文件名：===" + tmpFileName);
        File file = new File(tmpFileName);
        // 判断上传文件的保存目录是否存在
        if (!file.exists()){
            file.createNewFile();
            logger.debug("临时文件创建不成功。");
        }
        OutputStream out = new FileOutputStream(tmpFileName);
        ExcelUtils.listToExcel(sysJobList, fieldMap,"sheet",0, out);
		return R.ok().put("filePath", tmpFileName);
	}
	
}
